package com.app.micaihu.view.army.fragment

import android.animation.Animator
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.app.base.BaseMvpFragment
import com.app.http.bean.BaseBean
import com.app.micaihu.R
import com.app.micaihu.configure.ActivityRequestCode
import com.app.micaihu.configure.Config
import com.app.micaihu.configure.LoadType
import com.app.micaihu.configure.UmEventId
import com.app.micaihu.manager.UserInforManager
import com.app.micaihu.utils.InteractiveUtils
import com.app.micaihu.utils.MobclickAgentUtils
import com.app.micaihu.utils.StatServiceUtils
import com.app.micaihu.view.army.activity.ArmyMedalListActivity
import com.app.micaihu.view.army.adapter.ArmyFollowListAdapter
import com.app.micaihu.view.army.contract.ArmyFollowContract
import com.app.micaihu.view.army.presenter.ArmyFollowPresenter
import com.app.micaihu.view.bean.QuestionList
import com.app.micaihu.view.main.topic.PostDetailActivity
import com.app.micaihu.view.main.topic.PostSendActivity
import com.app.micaihu.view.main.view.WrapContentLinearLayoutManager
import com.app.micaihu.view.newsdetail.ImageShowActivity
import com.app.micaihu.view.user.userinfo.activity.MyHomepageDynamicActivity
import com.app.utils.biz.Biz
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.ViewUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.android.synthetic.main.army_joined_list_fragment.*

/**
 * 军团关注
 */
class ArmyFollowListFragment : BaseMvpFragment<ArmyFollowContract.View, ArmyFollowPresenter>(), ArmyFollowContract.View {

    override fun getLayoutId() = R.layout.army_joined_list_fragment
    override fun getPresenter() = ArmyFollowPresenter()
    var isRecycleViewScroll = false
    var isTop = false
    var isBottom = false
    var isAnimatorEnd = false
    private val armyFollowListAdapter: ArmyFollowListAdapter by lazy {
        val legionListAdapter = ArmyFollowListAdapter()
        rvList.layoutManager = WrapContentLinearLayoutManager(context)

        legionListAdapter.loadMoreModule.isAutoLoadMore = true
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        legionListAdapter.loadMoreModule.isEnableLoadMoreIfNotFullPage = false
        legionListAdapter
    }

    private val noLoginView: View by lazy {
        LayoutInflater.from(context).inflate(R.layout.army_follow_no_login_view, null)
    }

    override fun setData() {
        rvList.adapter = armyFollowListAdapter
        rvList.addOnScrollListener(MyScrollListener())
        LiveEventBus.get(Config.EventBus.loginSuccess, Boolean::class.java).observe(this, Observer {
            if (it) {
                ViewUtils.runOnUiThreadDelayed({ initLogin() }, 100)
            }
        })
        LiveEventBus.get(Config.EventBus.logOutSuccess, Boolean::class.java).observe(this, Observer {
            if (it) {
                ViewUtils.runOnUiThreadDelayed({ initLogin() }, 100)
            }
        })
    }

    override fun lazyLoad() {
        initLogin()
    }

    override fun addListeners() {
        armyFollowListAdapter.addChildClickViewIds(R.id.ivHeadPic, R.id.flLand, R.id.ivBigThumb, R.id.ivThumb0, R.id.ivThumb1, R.id.ivThumb2, R.id.ivHonourPic)
        armyFollowListAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.ivHeadPic -> {
                    val item = armyFollowListAdapter.getItem(position)
                    MyHomepageDynamicActivity.goToUserHomePage(activity, item.uid)
                }
                R.id.flLand -> {
                    InteractiveUtils.getInstance().laud((view as FrameLayout?)!!, null)
                }
                R.id.ivBigThumb,
                R.id.ivThumb0 -> {
                    val item = armyFollowListAdapter.getItem(position)
                    showImageDetail(item.imgList, 0)
                }
                R.id.ivThumb1 -> {
                    val item = armyFollowListAdapter.getItem(position)
                    showImageDetail(item.imgList, 1)
                }
                R.id.ivThumb2 -> {
                    val item = armyFollowListAdapter.getItem(position)
                    showImageDetail(item.imgList, 2)
                }
                R.id.ivHonourPic -> {
                    val item = armyFollowListAdapter.getItem(position)
                    val bundle = Bundle()
                    bundle.putString(Config.Extra.toUid, item.uid)
                    enterPager(ArmyMedalListActivity::class.java, bundle)
                }
            }
        }
        refreshLayout.setOnRefreshListener {
            // 这里的作用是防止下拉刷新的时候还可以上拉加载
            armyFollowListAdapter.loadMoreModule.isEnableLoadMore = false
            mPresenter?.refresh()
        }
        armyFollowListAdapter.loadMoreModule.setOnLoadMoreListener {
            mPresenter?.loadMore()
        }
        armyFollowListAdapter.setOnItemClickListener { adapter, view, position ->
            MobclickAgentUtils.event(UmEventId.topiclist_click, "关注")
            val item = armyFollowListAdapter.getItem(position)
            val intent = Intent(context, PostDetailActivity::class.java)
            intent.putExtra(Config.Extra.PARAMETER1, item.id)
            intent.putExtra(Config.Extra.eventValue, "关注")
            intent.putExtra(PostDetailActivity.COMMENT_SUM, item.replyNum)
            intent.putExtra(PostDetailActivity.PARISE_SUM, item.praiseNum)
            startActivityForResult(intent, ActivityRequestCode.REQUEST_CODE_TOPIC_DETAIL)
            activity?.overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain)
        }
        noLoginView.findViewById<Button>(R.id.btnLogin).setOnClickListener {
            UserInforManager.getInstance().toLoginPage(activity)
        }
        ivTopic.setOnClickListener {
            StatServiceUtils.event(Config.EventBauduId.team_post, "军团_发帖")
            val intent = Intent(context, PostSendActivity::class.java)
            ActivityUtils.startActivity(intent)
        }
    }

    private fun initLogin() {
        if (Biz.instance.uid().isEmpty()) {
            armyFollowListAdapter.setList(null)
            armyFollowListAdapter.setEmptyView(noLoginView)
            refreshLayout.setEnableRefresh(false)
        } else {
            refreshLayout.setEnableRefresh(true)
            armyFollowListAdapter.setEmptyView(loadingView)
            mPresenter?.refresh()
        }
    }

    /**
     * 展示大图
     *
     * @param imgList
     * @param i
     */
    private fun showImageDetail(imgList: ArrayList<String>, i: Int) {
        val intent = Intent(context, ImageShowActivity::class.java)
        intent.putStringArrayListExtra(Config.Extra.PARAMETER1, imgList)
        intent.putExtra(Config.Extra.PARAMETER2, i)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
        activity?.overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain)
    }

    override fun handleFollowList(video: BaseBean<QuestionList?>?, loadType: Int) {
        refreshLayout.finishRefresh(Config.delayRefresh)
        armyFollowListAdapter.loadMoreModule.isEnableLoadMore = true
        if (video == null) {
            if (armyFollowListAdapter.data.isNotEmpty()) {
                if (LoadType.TYPE_REFRESH_ERROR == loadType) {
                    ToastUtils.showShort(R.string.empty_network_error)
                } else {
                    armyFollowListAdapter.loadMoreModule.loadMoreFail()
                }
            } else {
                if (LoadType.TYPE_REFRESH_ERROR == loadType) {
                    armyFollowListAdapter.setEmptyView(errorView)
                } else {
                    armyFollowListAdapter.setEmptyView(getEmptyView())
                }
            }
        } else {
            if (video.isSuccess()) {
                video.data?.let {
                    if (LoadType.TYPE_REFRESH_SUCCESS == loadType) {
                        armyFollowListAdapter.setList(it.cmtList)
                    } else if (LoadType.TYPE_LOAD_MORE_SUCCESS == loadType) {
                        armyFollowListAdapter.addData(it.cmtList)
                    }
                    if (it.cmtList.isNullOrEmpty()) {
                        armyFollowListAdapter.setEmptyView(getEmptyView())
                        armyFollowListAdapter.loadMoreModule.loadMoreEnd()
                    } else {
                        armyFollowListAdapter.loadMoreModule.loadMoreComplete()
                    }
                }

            } else {
                ToastUtils.showShort(video.msg)
            }
        }

    }


    private inner class MyScrollListener : RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            when (newState) {
                RecyclerView.SCROLL_STATE_IDLE -> {
                    isRecycleViewScroll = false
                    showShareImage()
                }
                RecyclerView.SCROLL_STATE_DRAGGING, RecyclerView.SCROLL_STATE_SETTLING ->
                    if (!isRecycleViewScroll && !isBottom && !isTop) {
                        isRecycleViewScroll = true
                        hideShareImage()
                    }
            }
        }

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            val bottom = recyclerView.canScrollVertically(1)
            val top = recyclerView.canScrollVertically(-1)
            isBottom = !bottom
            isTop = !top
        }
    }

    @SuppressLint("ObjectAnimatorBinding")
    private fun showShareImage() {
        val animator = ObjectAnimator.ofFloat(ivTopic, "translationX", 0f)
        animator.duration = 600
        if (!isAnimatorEnd) {
            animator.startDelay = 1200
        }
        animator.start()
    }

    @SuppressLint("ObjectAnimatorBinding")
    private fun hideShareImage() {
        isAnimatorEnd = false
        val animator = ObjectAnimator.ofFloat(ivTopic, "translationX", SizeUtils.dp2px(70f).toFloat())
        animator.duration = 600
        animator.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {}
            override fun onAnimationEnd(animation: Animator) {
                isAnimatorEnd = true
            }

            override fun onAnimationCancel(animation: Animator) {}
            override fun onAnimationRepeat(animation: Animator) {}
        })
        animator.start()
    }
}